package com.yifa.health_manage;

import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayout;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yifa.health_manage.adapter.GridAdapter;
import com.yifa.health_manage.model.BloodValuesInfo;
import com.yifa.health_manage.model.DevicesListInfo;
import com.yifa.health_manage.model.XGridModel;
import com.yifa.health_manage.util.AndroidUtils;
import com.yifa.health_manage.util.SharePrefenceUtils;
import com.yifa.health_manage.util.WebServiceParmas;
import com.yifa.health_manage.util.WebServiceUtils;

public class XuetangListActivity extends Activity {

	private GridLayout gridLayout;

	private GridView gridView;

	private GridAdapter adapter;
	private DevicesListInfo listnew = null;

	private TextView Level0, Level1, Level2, Level3, Level4;

	private String timeType = "week", deviceType = "blood_glucose",
			device_sn = "123456", relative = "12345", startTime, endTime;

	private RadioGroup group;

	private List<TextView> texts = new ArrayList<TextView>();

	private int days = -7;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case WebServiceParmas.GET_BLOOD_DATA:
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(msg.obj.toString());
					JSONArray jsonArray = jsonObject.getJSONArray("data");
					if (jsonArray == null)
						return;
					Gson gson = new Gson();

					Type type = new TypeToken<List<BloodValuesInfo>>() {
					}.getType();
					List<BloodValuesInfo> mList = gson.fromJson(
							jsonArray.toString(), type);
					adapter.setDatas(handlerDate(mList));
				} catch (JSONException e) {
				}
				break;

			case WebServiceParmas.GET_DEVICE_FRIEND:
				JSONObject deviceI;
				try {
					deviceI = new JSONObject(msg.obj.toString());
					Gson gson = new Gson();
					Type type = new TypeToken<DevicesListInfo>() {
					}.getType();
					listnew = gson.fromJson(deviceI.toString(),
							DevicesListInfo.class);

				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (listnew == null || listnew.getData().size() <= 0) {
					// AndroidUtils.showToast(ChartActivity.this, "请添加用户设备");
					return;
				}
				if (listnew.getData().get(0).getRelative() == null
						|| listnew.getData().get(0).getRelative().size() <= 0) {
					return;
				}
				if (deviceType.equalsIgnoreCase("blood_glucose")) {
					if (SharePrefenceUtils
							.getSugarFriendId(XuetangListActivity.this).getId()
							.equalsIgnoreCase("")) {
						listnew.getData()
								.get(0)
								.getRelative()
								.get(0)
								.setDevice_sn(
										listnew.getData().get(0).getDevice_sn());
						SharePrefenceUtils.saveSugarFriendId(
								XuetangListActivity.this, listnew.getData()
										.get(0).getRelative().get(0));
					}
				} else {
					if (SharePrefenceUtils
							.getPressureFriendId(XuetangListActivity.this)
							.getId().equalsIgnoreCase("")) {
						listnew.getData()
								.get(0)
								.getRelative()
								.get(0)
								.setDevice_sn(
										listnew.getData().get(0).getDevice_sn());
						SharePrefenceUtils.savePressureFriendId(
								XuetangListActivity.this, listnew.getData()
										.get(0).getRelative().get(0));
					}
				}

				loadData(-7);

				break;

			case WebServiceParmas.SAVE_XUETANFG:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
					loadData(days);
				}

				break;
			case -1:
				AndroidUtils.showToast(XuetangListActivity.this, "请连接网络");
				break;
			default:
				break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_xuetang_list);
		gridLayout = (GridLayout) findViewById(R.id.gl_xuetang_layout);
		gridView = (GridView) findViewById(R.id.gv_xuetang);
		group = (RadioGroup) findViewById(R.id.radiogroup);
		Level0 = (TextView) findViewById(R.id.tv_text1);
		Level1 = (TextView) findViewById(R.id.tv_text2);
		Level2 = (TextView) findViewById(R.id.tv_text3);
		Level3 = (TextView) findViewById(R.id.tv_text4);
		Level4 = (TextView) findViewById(R.id.tv_text5);
		TextView chart = (TextView) findViewById(R.id.add_devices);
		chart.setVisibility(View.VISIBLE);
		chart.setText("图表");
		chart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(XuetangListActivity.this,
						ChartActivity.class);
				intent.putExtra("device_type", "blood_glucose");
				startActivity(intent);
			}
		});

		findViewById(R.id.activity_top_title).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						finish();
					}
				});
		adapter = new GridAdapter(this);
		gridView.setAdapter(adapter);

		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				BloodValuesInfo bloodValuesInfo = (BloodValuesInfo) adapter
						.getItem(position);
				if (!bloodValuesInfo.getValue().equals(""))
					createDialog(bloodValuesInfo);
			}
		});
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.radio0:
					days = -7;
					loadData(-7);
					break;
				case R.id.radio1:
					days = -30;
					loadData(-30);
					break;
				case R.id.radio2:
					days = -90;
					loadData(-90);
					break;
				case R.id.radio3:
					days = -120;
					loadData(-120);
					break;
				case R.id.radio4:
					loadData(-180);
					days = -180;
					break;

				default:
					break;
				}

			}
		});
		((TextView) findViewById(R.id.activity_top_title)).setText("血糖详情");
		new WebServiceUtils(this, mHandler).sendExecute(new String[] {
				SharePrefenceUtils.getAccount(this), deviceType },
				WebServiceParmas.GET_DEVICE_FRIEND, WebServiceParmas.HTTP_POST,
				"加载中...");

	}

	private List<BloodValuesInfo> handlerDate(List<BloodValuesInfo> datas) {
		List<BloodValuesInfo> datasss = new ArrayList<BloodValuesInfo>();

		Map<String, List<BloodValuesInfo>> map = new HashMap<String, List<BloodValuesInfo>>();
		for (BloodValuesInfo bloodValuesInfo : datas) {
			bloodValuesInfo.setPeriod(handlerTime(bloodValuesInfo) + "");
			DecimalFormat decimalFormat = new DecimalFormat("#.#");
			bloodValuesInfo.setValue(decimalFormat.format((Double
					.valueOf(bloodValuesInfo.getValue()) * 10 / 180)));
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm");
			SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM-dd");
			Date date = null;
			try {
				date = dateFormat.parse(bloodValuesInfo.getDatetime());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String time = dateFormat2.format(date);

			if (map.get(time) != null) {
				map.get(time).add(bloodValuesInfo);
			} else {
				List<BloodValuesInfo> value = new ArrayList<BloodValuesInfo>();
				value.add(bloodValuesInfo);
				map.put(time, value);
			}
			handlerXTdata(bloodValuesInfo);
		}
		Level0.setText(xtLevel0 + "");
		Level1.setText(xtLevel1 + "");
		Level2.setText(xtLevel2 + "");
		Level3.setText(xtLevel3 + "");
		Level4.setText(xtLevel4 + "");
		xtLevel0 = 0;
		xtLevel1 = 0;
		xtLevel2 = 0;
		xtLevel3 = 0;
		xtLevel4 = 0;
		Set<Entry<String, List<BloodValuesInfo>>> entries = map.entrySet();
		Iterator<Entry<String, List<BloodValuesInfo>>> iterator = entries
				.iterator();

		while (iterator.hasNext()) {
			XGridModel model = new XGridModel();
			Entry<String, List<BloodValuesInfo>> entry = iterator.next();
			List<BloodValuesInfo> bloodValuesInfos = entry.getValue();
			model.setTime(entry.getKey());
			Collections
					.sort(bloodValuesInfos, new BloodValuesInfo.PeriodType());
			int count = 1;
			int initPeriod = Integer.valueOf(bloodValuesInfos.get(0)
					.getPeriod());

			List<BloodValuesInfo> period0 = new ArrayList<BloodValuesInfo>();
			List<BloodValuesInfo> period1 = new ArrayList<BloodValuesInfo>();
			List<BloodValuesInfo> period2 = new ArrayList<BloodValuesInfo>();
			List<BloodValuesInfo> period3 = new ArrayList<BloodValuesInfo>();
			List<BloodValuesInfo> period4 = new ArrayList<BloodValuesInfo>();
			List<BloodValuesInfo> period5 = new ArrayList<BloodValuesInfo>();
			List<BloodValuesInfo> period6 = new ArrayList<BloodValuesInfo>();
			List<BloodValuesInfo> period7 = new ArrayList<BloodValuesInfo>();
			for (BloodValuesInfo info : bloodValuesInfos) {
				int period = Integer.valueOf(info.getPeriod());
				switch (period) {
				case 0:
					period0.add(info);
					break;
				case 1:
					period1.add(info);
					break;
				case 2:
					period2.add(info);
					break;
				case 3:
					period3.add(info);
					break;
				case 4:
					period4.add(info);
					break;
				case 5:
					period5.add(info);
					break;
				case 6:
					period6.add(info);
					break;
				case 7:
					period7.add(info);
					break;
				default:
					break;
				}
			}
			List<Integer> sizes = new ArrayList<Integer>();
			sizes.add(period0.size());
			sizes.add(period1.size());
			sizes.add(period2.size());
			sizes.add(period3.size());
			sizes.add(period4.size());
			sizes.add(period5.size());
			sizes.add(period6.size());
			sizes.add(period7.size());
			Integer max = Collections.max(sizes);

			List<BloodValuesInfo> data = new ArrayList<BloodValuesInfo>();
			int data0 = 0, data1 = 0, data2 = 0, data3 = 0, data4 = 0, data5 = 0, data6 = 0, data7 = 0;
			for (int i = 0; i < max * 9; i++) {
				int index = i % 9;
				if (index == 0) {
					BloodValuesInfo info = new BloodValuesInfo();
					info.setDatetime(entry.getKey());
					data.add(info);
				} else if (index == 1) {
					if (period0.size() > data0) {
						data.add(period0.get(data0));
					} else {
						BloodValuesInfo info = new BloodValuesInfo();
						data.add(info);
					}
					data0++;
				} else if (index == 2) {
					if (period1.size() > data1) {
						data.add(period1.get(data1));
					} else {
						BloodValuesInfo info = new BloodValuesInfo();
						data.add(info);
					}
					data1++;
				} else if (index == 3) {
					if (period2.size() > data2) {
						data.add(period2.get(data2));
					} else {
						BloodValuesInfo info = new BloodValuesInfo();
						data.add(info);
					}
					data2++;
				} else if (index == 4) {
					if (period3.size() > data3) {
						data.add(period3.get(data3));
					} else {
						BloodValuesInfo info = new BloodValuesInfo();
						data.add(info);
					}
					data3++;
				} else if (index == 5) {
					if (period4.size() > data4) {
						data.add(period4.get(data4));
					} else {
						BloodValuesInfo info = new BloodValuesInfo();
						data.add(info);
					}
					data4++;
				} else if (index == 6) {
					if (period5.size() > data5) {
						data.add(period5.get(data5));
					} else {
						BloodValuesInfo info = new BloodValuesInfo();
						data.add(info);
					}
					data5++;
				} else if (index == 7) {
					if (period6.size() > data6) {
						data.add(period6.get(data6));
					} else {
						BloodValuesInfo info = new BloodValuesInfo();
						data.add(info);
					}
					data6++;
				} else if (index == 8) {
					if (period7.size() > data7) {
						data.add(period7.get(data7));
					} else {
						BloodValuesInfo info = new BloodValuesInfo();
						data.add(info);
					}
					data7++;
				}
			}
			datasss.addAll(data);
		}
		return datasss;
	}

	int xtLevel0 = 0;
	int xtLevel1 = 0;
	int xtLevel2 = 0;
	int xtLevel3 = 0;
	int xtLevel4 = 0;

	private void handlerXTdata(BloodValuesInfo bloodValuesInfo) {
		float data = Float.valueOf(bloodValuesInfo.getValue().equals("") ? "0"
				: bloodValuesInfo.getValue());
		if (data < 3.3) {
			xtLevel0++;
		} else if (3.3 <= data && data < 3.9) {
			xtLevel1++;
		} else if (4.4 <= data && data < 10) {
			xtLevel2++;
		} else if (10 <= data && data < 13) {
			xtLevel3++;
		} else if (13 <= data) {
			xtLevel4++;
		}
	}

	/**
	 * 
	 * @param time
	 * @return
	 */
	private int handlerTime(BloodValuesInfo bloodValuesInfo) {

		if (bloodValuesInfo.getPeriod() != null
				&& !bloodValuesInfo.getPeriod().equals("")) {
			return Integer.valueOf(bloodValuesInfo.getPeriod());
		}

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = null;
		try {
			date = dateFormat.parse(bloodValuesInfo.getDatetime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);

		int value = 0;
		int hours = calendar.get(Calendar.HOUR_OF_DAY);
		if (0 < calendar.HOUR_OF_DAY && calendar.HOUR_OF_DAY < 3) {
			return 0;
		} else if (3 <= calendar.HOUR_OF_DAY && calendar.HOUR_OF_DAY < 6) {
			return 1;
		} else if (hours == 6) {
			if (calendar.MINUTE < 30) {
				return 1;
			} else {
				return 2;
			}
		} else if (6 < hours && hours < 10) {
			return 2;
		} else if (10 <= hours && hours < 12) {
			return 3;
		} else if (12 <= hours && hours < 15) {
			return 4;
		} else if (15 <= hours && hours < 18) {
			return 5;
		} else if (18 <= hours && hours < 21) {
			return 6;
		} else if (21 <= hours && hours < 23) {
			return 7;
		}
		return 0;
	}

	public void loadData(int days) {
		Calendar calendar = Calendar.getInstance();
		DateFormat dateFormat = new DateFormat();
		endTime = (String) dateFormat.format("yyyy.MM.dd", calendar);
		calendar.add(Calendar.DATE, days);
		startTime = (String) dateFormat.format("yyyy.MM.dd", calendar);
		relative = SharePrefenceUtils.getSugarFriendId(this).getId();
		device_sn = SharePrefenceUtils.getSugarFriendId(this).getDevice_sn();
		if (!relative.equals("") && !device_sn.equals("")) {
			String start = startTime.replace(".", "-");
			String end = endTime.replace(".", "-");

			new WebServiceUtils(this, mHandler).sendExecute(new String[] {
					SharePrefenceUtils.getAccount(XuetangListActivity.this),
					deviceType, device_sn, relative, timeType, start, end },
					WebServiceParmas.GET_BLOOD_DATA,
					WebServiceParmas.HTTP_POST, "加载中...");
		}

	}

	private Dialog dialog;

	private void createDialog(final BloodValuesInfo info) {
		dialog = new Dialog(XuetangListActivity.this, R.style.ThemeDialog);
		View view = LayoutInflater.from(XuetangListActivity.this).inflate(
				R.layout.dialog_xuetang_layout, null);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

		LayoutParams layoutParams = new LayoutParams(0, 0);
		layoutParams.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8);
		layoutParams.height = (int) (getResources().getDisplayMetrics().widthPixels);
		dialog.setContentView(view, layoutParams);

		TextView textView = (TextView) view.findViewById(R.id.tv_xuetang);
		TextView textView0 = (TextView) view.findViewById(R.id.tv_prieod0);
		TextView textView1 = (TextView) view.findViewById(R.id.tv_prieod1);
		TextView textView2 = (TextView) view.findViewById(R.id.tv_prieod2);
		TextView textView3 = (TextView) view.findViewById(R.id.tv_prieod3);
		TextView textView4 = (TextView) view.findViewById(R.id.tv_prieod4);
		TextView textView5 = (TextView) view.findViewById(R.id.tv_prieod5);
		TextView textView6 = (TextView) view.findViewById(R.id.tv_prieod6);
		TextView textView7 = (TextView) view.findViewById(R.id.tv_prieod7);

		texts.add(textView0);
		texts.add(textView1);
		texts.add(textView2);
		texts.add(textView3);
		texts.add(textView4);
		texts.add(textView5);
		texts.add(textView6);
		texts.add(textView7);
		Button save = (Button) view.findViewById(R.id.btn_save);
		textView.setText(info.getValue());
		priod = Integer.valueOf(info.getPeriod());

		switch (priod) {
		case 0:
			textView0.setBackgroundResource(R.drawable.text_prieod_bg_select);
			textView0.setTextColor(Color.parseColor("#FFFFFF"));
			break;
		case 1:
			textView1.setBackgroundResource(R.drawable.text_prieod_bg_select);
			textView1.setTextColor(Color.parseColor("#FFFFFF"));
			break;
		case 2:
			textView2.setBackgroundResource(R.drawable.text_prieod_bg_select);
			textView2.setTextColor(Color.parseColor("#FFFFFF"));
			break;
		case 3:
			textView3.setBackgroundResource(R.drawable.text_prieod_bg_select);
			textView3.setTextColor(Color.parseColor("#FFFFFF"));
			break;
		case 4:
			textView4.setBackgroundResource(R.drawable.text_prieod_bg_select);
			textView4.setTextColor(Color.parseColor("#FFFFFF"));
			break;
		case 5:
			textView5.setBackgroundResource(R.drawable.text_prieod_bg_select);
			textView5.setTextColor(Color.parseColor("#FFFFFF"));
			break;
		case 6:
			textView6.setBackgroundResource(R.drawable.text_prieod_bg_select);
			textView6.setTextColor(Color.parseColor("#FFFFFF"));
			break;
		case 7:
			textView7.setBackgroundResource(R.drawable.text_prieod_bg_select);
			textView7.setTextColor(Color.parseColor("#FFFFFF"));
			break;

		default:
			break;
		}

		textView0.setOnClickListener(new onClickListener());
		textView1.setOnClickListener(new onClickListener());
		textView2.setOnClickListener(new onClickListener());
		textView3.setOnClickListener(new onClickListener());
		textView4.setOnClickListener(new onClickListener());
		textView5.setOnClickListener(new onClickListener());
		textView6.setOnClickListener(new onClickListener());
		textView7.setOnClickListener(new onClickListener());
		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				new WebServiceUtils(XuetangListActivity.this, mHandler).sendExecute(
						new String[] {
								SharePrefenceUtils
										.getAccount(XuetangListActivity.this),
								deviceType, device_sn, info.getId(),
								priod + "" }, WebServiceParmas.SAVE_XUETANFG,
						WebServiceParmas.HTTP_POST, "加载中...");
			}
		});
		dialog.show();
	}

	int priod = 0;

	class onClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.tv_prieod0:
				priod = 0;
				break;
			case R.id.tv_prieod1:
				priod = 1;
				break;
			case R.id.tv_prieod2:
				priod = 2;
				break;
			case R.id.tv_prieod3:
				priod = 3;
				break;
			case R.id.tv_prieod4:
				priod = 4;
				break;
			case R.id.tv_prieod5:
				priod = 5;
				break;
			case R.id.tv_prieod6:
				priod = 6;
				break;
			case R.id.tv_prieod7:
				priod = 7;
				break;

			default:
				break;
			}
			for (TextView text : texts) {
				text.setBackgroundResource(R.drawable.text_prieod_lg);
				text.setTextColor(Color.parseColor("#000000"));
			}

			v.setBackgroundResource(R.drawable.text_prieod_bg_select);
			((TextView) v).setTextColor(Color.parseColor("#FFFFFF"));

		}
	}
}
